package com.itheima.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/findStudents")
public class findStudents extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String realPath = this.getServletContext().getRealPath("/stu.txt");
        InputStreamReader isr = new InputStreamReader(new FileInputStream(realPath),"UTF-8");
        BufferedReader br = new BufferedReader(isr);
        ArrayList<Student> listStu = new ArrayList<>();
        String len;
        while ((len = br.readLine()) != null){
            Student student = new Student();
            String[] split = len.split(",");
            student.setUsername(split[0]);
            student.setAge(Integer.parseInt(split[1]));
            student.setScore(Integer.parseInt(split[2]));
            listStu.add(student);

        }
        HttpSession session = request.getSession();
        session.setAttribute("list",listStu);
        response.sendRedirect(request.getContextPath()+"/find.jsp");
        /*response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        for (Student student : listStu) {
            writer.print("姓名:"+student.getUsername()+" 年龄:"+student.getAge()+" 分数:"+student.getScore()+"<br/>");
        }*/

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
